/*================================================================
*   文件名称：main.cpp
*   创 建 者：yang qiang
*   创建日期：2018年07月15日
*   描    述：
*   Copyright (C) 2018 All rights reserved.
*   
================================================================*/


#include <iostream>
#include <vector>
#include <stack>

using namespace std;

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: A Tree
     * @return: Postorder in ArrayList which contains node values.
     */
    vector<int> postorderTraversal(TreeNode * root) {
        // write your code here
        vector<int> result;
        if( !root ){
            return result;
        }
        
        stack<TreeNode *> s;
        TreeNode *cur = NULL;
        TreeNode *pre = NULL;
        s.push(root);
        while( !s.empty() ){
            cur = s.top();
            if( (!cur->left && !cur->right) || (pre && (pre == cur->left || pre == cur->right))  ){
                result.push_back(cur->val);
                pre = cur;
                s.pop();
            }else{
                if( cur->right ){
                    s.push(cur->right);
                }
                if( cur->left ){
                    s.push(cur->left);
                }
            }
        }
    }	
};
